package com.jn.server;


import com.jn.server.utils.MyAnnotation;
import javafx.beans.binding.ObjectExpression;

import javax.swing.*;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.PrintStream;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Parameter;
import java.net.Socket;
import java.util.*;

/**
 * @author 江南大学1033190417
 * @date 2022/4/7 19:52
 */
public class ConnectionThread extends Thread {
    public Socket client;//连接Web浏览器的socket字
    public int counter;//计数器
    public String path;
    public JTextArea lianjie;
    public JLabel fasong;
    public JLabel shoudao;

    public ConnectionThread(Socket cl, int c, String path, JTextArea lianjie, JLabel fasong, JLabel shoudao) {
        this.client = cl;
        this.counter = c;
        this.path = path;
        this.lianjie = lianjie;
        this.fasong = fasong;
        this.shoudao = shoudao;
    }


    @Override
    public void run() {
        Result result = new Result();
        try {
            result.IP = client.getInetAddress().toString();//客户机IP地址
            result.port = client.getPort();//客户机端口号
            PrintStream outstream = new PrintStream(client.getOutputStream());
            DataInputStream instream = new DataInputStream(client.getInputStream());
            //读取Web浏览器提交的请求信息
            String inline = instream.readLine();//GET /index.html HTTP/1.1
            String requestType = getRequestType(inline);//请求类型
            result.method = requestType;
            String path = getPath(inline);//请求路径
            result.file = getUrl(inline);
            Map<String, Object> requestParams = getRequestParams(inline);//请求参数
            Object res = MyAnnotation.getIndex(path, requestType, requestParams);
            if (res!=null){
                result.isExist=true;
                outstream.println("HTTP/1.0 200OK");
                outstream.println("mime_version: 1.0");
                outstream.println("Content-Type: text/html;charset=utf-8");
                int length = res.toString().length();
                result.length=length;
                outstream.println("Content_Length: " + length);
                outstream.println("");
                outstream.println("<html><head><title>Found</title></head> <body><h1> " + res + "</h1></body ></html> ");
                outstream.flush();
                outstream.close();
            }else {
                result.isExist=false;
                String notfound = "<html><head><title> Not Found</title></head> <body><h1> Error404-File notfound </h1></body ></html> ";
                outstream.println("HTTP/1.0 404 no found");
                outstream.println("Content-Type: text/html;charset=utf-8");
                outstream.println("Content_Length: " + notfound.length() + 2);
                result.length = notfound.length() + 2;
                outstream.println("");
                outstream.println(notfound);
                outstream.flush();
                outstream.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
            synchronized (ConnectionThread.class) {
                lianjie.append("\n异常1：\n" + e + "\n");
            }
        }
        synchronized (ConnectionThread.class) {
            lianjie.append(result + "\n");
            Integer num = Integer.valueOf(fasong.getText());
            Integer length = result.length;
            num += (length == null ? 0 : length);
            fasong.setText(num + "");
            shoudao.setText((Integer.parseInt(shoudao.getText()) + 1) + "");
        }
    }


    //获取要访问的路径
    public static String getPath(String s) {
        String[] split = s.split(" ");
        if (!s.contains("?")) {
            return split[1].replace("/", "");
        } else {
            String url = split[1];
            return url.substring(1, url.indexOf("?"));
        }
    }

    //获取请求url
    public static String getUrl(String s) {
        return s.substring(s.indexOf(" "), s.lastIndexOf(" "));
    }

    //获得访问的参数值
    public static Map<String, Object> getRequestParams(String s) {
        if (!s.contains("?")) {
            return null;
        }
        String s1 = s.substring(s.indexOf("?") + 1, s.lastIndexOf(" "));
        String[] split = s1.split("&");
        Map<String, Object> result = new HashMap<>();
        for (String s2 : split) {
            String[] strings = s2.split("=");
            String name = strings[0];
            String value = strings[1];
            result.put(name, value);
        }
        return result;
    }

    /**
     * 拿到请求的方法
     *
     * @param inline GET /index.html HTTP/1.1
     * @return GET, POST, PUT, DELETE
     */
    public static String getRequestType(String inline) {
        try {
            return inline.substring(0, inline.indexOf(" "));
        } catch (Exception e) {
            return null;
        }
    }

    //把指定文件发送给Web浏览器
    void sendFile(PrintStream outs, File file) {
        try {
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            int len = (int) file.length();
            byte[] buf = new byte[len];
            in.readFully(buf);
            outs.write(buf, 0, len);
            outs.flush();
            in.close();
        } catch (Exception e) {

            System.out.println("Error retrieving file.");

            System.exit(1);

        }

    }

    public static void main(String[] args) {
        System.out.println(getRequestParams("GET /index?name=zs&age=20 HTTP/1.1"));
        System.out.println(getUrl("GET /index?name=zs&age=20 HTTP/1.1"));
    }

}
